package com.one.group.service.impl;

import com.one.group.enums.ErrorCode;
import com.one.group.exception.BusinessException;
import com.one.group.service.AdminService;
import com.one.group.service.chatHistoryService;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * {@code @Create:}  2025-10-14  15 : 19
 * {@code @Author:} Cherry
 * {@code @ToAuthor:} 凡是发生,皆有利于我。
 * ------------------------------------
 * {@code @note:}
 */

@SuppressWarnings({"all"})
@Service
public class ChatHistoryServiceImpl implements chatHistoryService {
    @DubboReference
    private AdminService adminService;
    @Resource
    private RedisTemplate redisTemplate;

    // 构建 Redis Key，例如：chat:history:{userId}:{type}
    private String buildKey(String type) {
        Object userId = redisTemplate.opsForValue().get("userId");
        if (userId == null) {
            throw new BusinessException(ErrorCode.USER_NOT_EXIST, "当前线程未设置用户id");
        }
        return "chat:history:" + userId + ":" + type;
    }

    @Override
    public void save(String type, String chatId) {
        String key = buildKey(type);
        redisTemplate.opsForSet().add(key, chatId);
    }

    @Override
    public List<String> getChatIds(String type) {
        String key = buildKey(type);
        Set<String> chatIds = redisTemplate.opsForSet().members(key);
        return chatIds != null ? new ArrayList<>(chatIds) : Collections.emptyList();
    }
}
